package com.javaranger.news.controller;


import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.javaranger.news.entity.Result;
import com.javaranger.news.entity.query.QueryRequest;
import com.javaranger.news.service.QueryService;

@Controller()
public class QueryController {
	private static final Logger log = Logger.getLogger(QueryController.class);
	@Autowired
	QueryService queryService;
	
	@RequestMapping(value = "/query")
	public void query(HttpServletResponse response, @Valid final QueryRequest request,
			final BindingResult bindResult){
		if (bindResult.hasErrors()) {
			renderJson(new Result(), response);
		} else {
			renderJson(queryService.query(request), response);
		}
	}
	
	private void renderJson(Object object, HttpServletResponse response) {
		MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
		try {
			converter.write(object, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
		} catch (HttpMessageNotWritableException e) {
			log.error(e);
		} catch (IOException e) {
			log.error(e);
		}
	}
}
